package com.atguigu.gmall.activity.controller;
/**
 * 加油！你是最胖的
 *
 * @author TaiXiaoDong on 2023/3/24.
 * @version 1.0
 */

import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.activity.util.CacheHelper;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.OrderRecode;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.client.OrderFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**



 */
@RestController
@RequestMapping("/api/activity/seckill")
@SuppressWarnings("all")
public class SeckillGoodsApiController {

    @Autowired
    private SeckillGoodsService seckillGoodsService;
    @Autowired
    private RabbitService rabbitService;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderFeignClient orderFeignClient;

    /**
     POST/api/activity/seckill/auth/submitOrder
     保存秒杀订单

    */
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, HttpServletRequest request){
        //获取用户id ，是前端请求头里带着的用户id
        String userId = AuthContextHolder.getUserId(request);

        //设置userId
        orderInfo.setUserId(Long.valueOf(userId));

        //通过openFeign远程调用保存订单接口
        Long orderId = orderFeignClient.submitOrder(orderInfo);

        //判断 订单不为空
        if (orderId == null) {
            return Result.fail().message("保存订单失败，请重试……");
        }

        //删除redis临时秒杀订单
        redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS).delete(userId);

        //保存redis的下单记录
        redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS_USERS).put(userId,orderId);

        return Result.ok(orderId);
    }



    /**
     接口路径：GET/api/activity/seckill/auth/trade
     秒杀下单确认

    */
    @GetMapping("/auth/trade")
    public Result trade(HttpServletRequest request){

        //获取用户id
        String userId = AuthContextHolder.getUserId(request);
        //创建集合封装数据
        Map<String, Object> resultMap = new HashMap<>();

        //查询用户地址列表
        List<UserAddress> userAddressList = userFeignClient.findUserAddressListByUserId(Long.valueOf(userId));

        //获取秒杀订单
        OrderRecode orderRecode = (OrderRecode) redisTemplate.boundHashOps(RedisConst.SECKILL_ORDERS).get(userId);

        //判断
        if (orderRecode == null) {
            return Result.fail().message("非法请求");
        }

        //获取秒杀商品信息
        SeckillGoods seckillGoods = orderRecode.getSeckillGoods();

        //创建集合封装订单明细数据
        ArrayList<OrderDetail> orderDetailList = new ArrayList<>();
        OrderDetail orderDetail=new OrderDetail();
        orderDetail.setSkuId(seckillGoods.getSkuId());
        orderDetail.setSkuName(seckillGoods.getSkuName());
        orderDetail.setImgUrl(seckillGoods.getSkuDefaultImg());
        orderDetail.setOrderPrice(seckillGoods.getCostPrice());
        orderDetail.setSkuNum(orderRecode.getNum());
        orderDetailList.add(orderDetail);

        //计算总金额
        OrderInfo orderInfo=new OrderInfo();
        orderInfo.setOrderDetailList(orderDetailList);

        //计算
        orderInfo.sumTotalAmount();

        resultMap.put("totalAmount",orderInfo.getTotalAmount());
        resultMap.put("userAddressList",userAddressList);
        resultMap.put("detailArrayList",orderDetailList);
        resultMap.put("totalNum",1);

        return Result.ok(resultMap);
    }



    /**
     接口路径：GET/api/activity/seckill/auth/checkOrder/{skuId}
     检查秒杀状态

    */
    @GetMapping("/auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable String skuId,HttpServletRequest request){

        //获取用户id
        String userId = AuthContextHolder.getUserId(request);

        return seckillGoodsService.checkOrder(userId,skuId);
    }



    /**
     接口路径：POST/api/activity/seckill/auth/seckillOrder/{skuId}
     秒杀下单

    */
    @PostMapping("/auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable String skuId,HttpServletRequest request){

        //获取抢购码
        String skuIdStr = request.getParameter("skuIdStr");
        //获取用户id
        String userId = AuthContextHolder.getUserId(request);
        //校验抢购码
        if (!MD5.encrypt(userId+skuId).equals(skuIdStr)) {
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }

        //获取状态位
        String state = (String) CacheHelper.get(skuId);
        //判断
        if (StringUtils.isEmpty(state)) {

            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }

        //判断是否还有库存
        if ("1".equals(state)) {

            //封装数据对象
            UserRecode userRecode = new UserRecode();
            userRecode.setUserId(userId);
            userRecode.setSkuId(Long.valueOf(skuId));


            //发送消息到mq排队 userId skuId
            rabbitService.sendMessaged(
                    MqConst.EXCHANGE_DIRECT_SECKILL_USER,
                    MqConst.ROUTING_SECKILL_USER,
                    userRecode
            );


        }else {

            return Result.build(null,ResultCodeEnum.SECKILL_FINISH);
        }
        return Result.ok();
    }



    /**
     接口路径：GET/api/activity/seckill/auth/getSeckillSkuIdStr/{skuId}
     获取下单码

    */
    @GetMapping("/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId,HttpServletRequest request){

        //获取用户id
        String userId = AuthContextHolder.getUserId(request);

        //查询获取秒杀商品详情
        SeckillGoods seckillGoods = seckillGoodsService.getSeckillGoods(skuId);
        //判断
        if (seckillGoods != null) {
            //判断是否合法时
            Date curdDate = new Date();
            //比较时间 当前时间大于开始时间   当前时间小于结束时间
            //开始时间 当前时间 结束时间
            if (DateUtil.dateCompare(seckillGoods.getStartTime(), curdDate) &&
            DateUtil.dateCompare(curdDate,seckillGoods.getEndTime())){

                //生成抢购码
                String skuStr = MD5.encrypt(userId + skuId);


                return Result.ok(skuStr);

            }

        }

        return Result.build(null,ResultCodeEnum.ILLEGAL_REQUEST);
    }





    /**
     GET/api/activity/seckill/findAll
     获取秒杀商品列表：select * from seckill_goods

    */
    @GetMapping("/findAll")
    public Result findAll(){

        //调用Service中的方法 实现查询秒杀商品的功能
        List<SeckillGoods> seckillGoods = seckillGoodsService.findAll();

        return Result.ok(seckillGoods);
    }


    /**
     接口路径：GET/api/activity/seckill/getSeckillGoods/{skuId}
     查询秒杀商品详情：select * from seckill_goods where #{skuId}

    */
    @GetMapping("/getSeckillGoods/{skuId}")
    public Result getSeckillGoods(@PathVariable Long skuId){

        //调用Service层中的方法 实现获取秒杀商品详情的功能
        SeckillGoods seckillGoods = seckillGoodsService.getSeckillGoods(skuId);

        return Result.ok(seckillGoods);
    }


}
